
import 'package:in_app_purchase/in_app_purchase.dart';
import 'dart:async'; // 新添加

class GMInAppPurchaseTool {
  static final InAppPurchase _iap = InAppPurchase.instance;
  static late StreamSubscription _subscription;
  static Function? onPurchaseSuccess; // 新添加
  static Function? onPurchaseLoading; // 新添加

  static void listenToPurchaseStream() {
    // 新添加
    _subscription = _iap.purchaseStream.listen((purchases) {
      for (var purchase in purchases) {
        if (purchase.status == PurchaseStatus.purchased) {
          // 验证购买凭证
          // 发放货币
          // 完成购买
          completePurchase(purchase);
          onPurchaseSuccess?.call(); // 新添加
        } else if (purchase.status == PurchaseStatus.error) {
          // 处理错误
          // print('Purchase error: ${purchase.error?.message}');
          completePurchase(purchase); // 在这里添加，以确保交易完成
        }
      }
    });
  }

  static void cancelSubscription() {
    // 新添加
    _subscription.cancel();
  }

  static Future<bool> isAvailable() async {
    final bool available = await _iap.isAvailable();
    // print('IAP is available: $available');
    return available;
  }

  static Future<List<ProductDetails>> getProductDetails(
      List<String> ids) async {
    // print('Querying product IDs: $ids'); // 新增
    final ProductDetailsResponse response =
        await _iap.queryProductDetails(ids.toSet());
    // print('Query result: $response'); // 新增
    if (response.notFoundIDs.isNotEmpty) {
      print('Some products were not found: ${response.notFoundIDs}');
    }
    // print('Found products: ${response.productDetails}');
    return response.productDetails;
  }

  static Stream<List<PurchaseDetails>> get purchaseStream =>
      _iap.purchaseStream;

  static Future<void> buyProduct(ProductDetails productDetails) async {
    try {
      onPurchaseLoading?.call(); // 新添加
      // print('Attempting to buy product: ${productDetails.id}');
      final PurchaseParam purchaseParam = PurchaseParam(
        productDetails: productDetails,
      );
      await _iap.buyNonConsumable(purchaseParam: purchaseParam);
    } catch (e) {
      // print('An error occurred while buying the product: $e');
      // 这里您可以添加更多的错误处理逻辑
    }
  }

  static Future<void> completePurchase(PurchaseDetails purchaseDetails) async {
    // print('Completing purchase for product: ${purchaseDetails.productID}'); // 新增日志
    await _iap.completePurchase(purchaseDetails);
  }

  static Future<void> restorePurchases() async {
    await _iap.restorePurchases();
  }
}
